package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.service.IPictureService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class PictureServiceImpl implements IPictureService {

    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private AlbumMapper albumMapper;

    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        log.debug("开始处理【添加图片】的业务，参数：{}",pictureAddNewDTO);
        //调用AlbumMapper的getStandardById()查询相册数据是否存在
        Long albumId = pictureAddNewDTO.getAlbumId();
        AlbumStandardVO album = albumMapper.getStandardById(albumId);
        if (album == null) {
            //是：添加图片失败，相册不存在，抛出异常
            String message = "添加图片失败，相册不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //创建Picture对象
        Picture picture = new Picture();
        //将参数对象中的各属性值复制到以上新创建的Picture类的对象中
        BeanUtils.copyProperties(pictureAddNewDTO,picture);

        log.debug("即将向数据库插入数据：{}",picture);
        int rows = pictureMapper.insert(picture);
        if (rows != 1) {
            String message = "插入数据失败。服务器忙，请稍后在尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据id删除图片】的业务，参数：{}",id);
        //调用Mapper的getStandardById()检查图片是否存在；
        Object queryResult = pictureMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除图片失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("即将执行删除数据，id：{}",id);
        int rows = pictureMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除数据失败。服务器忙，请稍后在尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }
}
